package bmt.audioplayer.app.controller.player;

import android.media.MediaPlayer;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SearchView;
import android.widget.SeekBar;

import java.io.Serializable;
import java.util.ArrayList;

import bmt.audioplayer.app.R;
import bmt.audioplayer.app.PlayerActivity;
import bmt.audioplayer.app.model.player.Song;
import bmt.audioplayer.app.util.PlayerHelper;
import bmt.audioplayer.app.util.SongManager;

/**
 * Created by Tuan on 4/21/14.
 */
public class PlayerController implements View.OnClickListener, MediaPlayer.OnCompletionListener, SeekBar.OnSeekBarChangeListener, Serializable,
        AdapterView.OnItemClickListener, SearchView.OnQueryTextListener, SearchView.OnCloseListener {
    PlayerActivity playerActivity;
    Handler playerHandler;
    PlayerHelper playerHelper;
    SongManager songManager;
    PlayerPagerAdapter playerPagerAdapter;
    public static int NUMBER_PLAYER_PAGE = 2;

    public PlayerController(PlayerActivity playerActivity) {
        this.playerActivity = playerActivity;
        playerHandler = new Handler();
        playerHelper = new PlayerHelper();
        songManager = new SongManager(playerActivity);
        playerPagerAdapter = new PlayerPagerAdapter(playerActivity.getSupportFragmentManager());
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();

        switch (viewId) {
            case R.id.player_btn_next:
            case R.id.player_btn_pre:
                songManager.calculateSongIndex(viewId);
                playerActivity.playSong(songManager.getPlaySong());
                break;
            case R.id.player_btn_play:
                playerActivity.onTogglePlayMode();
                break;
            case R.id.player_btn_repeat:
                this.onToggleRepeatMode();
                break;
            case R.id.player_btn_shuff:
                this.onToggleShuffMode();
                break;
            default:
                break;
        }
    }

    public void onToggleRepeatMode() {
        if (songManager.isRepeat() == true) {
            songManager.setRepeat(false);
            playerActivity.getBtnRepeat().setImageResource(R.drawable.repeatdefault);
        } else {
            songManager.setRepeat(true);
            playerActivity.getBtnRepeat().setImageResource(R.drawable.repeatfocus);
        }
    }

    public void onToggleShuffMode() {
        int currentSong = songManager.getPlayList().get(songManager.getCurrentIndex());
        if (songManager.isShuff() == true) {
            songManager.setShuff(false);
            songManager.resetPlaylist();
            playerActivity.getBtnShuff().setImageResource(R.drawable.shufferdefault);
        } else {
            songManager.setShuff(true);
            songManager.shuffPlaylist();
            playerActivity.getBtnShuff().setImageResource(R.drawable.shufflefocus);
        }
        songManager.resetCurrentIndex(currentSong);
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        /* Avoid play song in start up*/
        if (songManager.isFirstTime() == false) {
            songManager.calculateSongIndex(R.id.player_btn_next);
            playerActivity.playSong(songManager.getPlaySong());
        }
    }

    public boolean isFirstTime() {
        return songManager.isFirstTime();
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        playerHandler.removeCallbacks(playerUpdateTime);
        playerActivity.pauseLineAnimation();
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        playerHandler.removeCallbacks(playerUpdateTime);
        long totalDuration = playerActivity.getMediaPlayer().getDuration();
        int currentPosition = playerHelper.progressToTimer(seekBar.getProgress(), totalDuration);
        playerActivity.getMediaPlayer().seekTo(currentPosition);
        playerActivity.restartLineAnimation();
        updateProgress();
    }


    public void updateProgress() {
        playerHandler.postDelayed(playerUpdateTime, 10);
    }

    /**
     * Runnable to update time
     */
    private Runnable playerUpdateTime = new Runnable() {
        long totalDuration;
        long currentDuration;
        long leftTime;

        @Override
        public void run() {
            totalDuration = playerActivity.getMediaPlayer().getDuration();
            currentDuration = playerActivity.getMediaPlayer().getCurrentPosition();
            leftTime = totalDuration - currentDuration;

            playerActivity.getTotalDuration().setText(playerHelper.miliSecondsToTimer(leftTime));
            int progress = playerHelper.getProgressPercentage(currentDuration, totalDuration);
            playerActivity.getSongSeekBar().setProgress(progress);
            playerHandler.postDelayed(this, 10);
        }
    };

    public void clearRunTime() {
        playerHandler.removeCallbacks(playerUpdateTime);
    }

    public long getTimeLeft() {
        return playerHelper.getTimeLeft(playerActivity.getMediaPlayer());
    }

    public String miliSecondsToTimer(long duration) {
        return playerHelper.miliSecondsToTimer(duration);
    }

    public byte[] getSongPicture() {
        return songManager.getPlaySong().getImg();
    }

    public void playFirstSong() {
        if (songManager.getPlayList().size() > 0) {
            playerActivity.playSong(songManager.getPlaySong());
        }
    }

    public ArrayList<Song> getAllSong() {
        return songManager.getSongsList();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        playerActivity.showPlayerControl();

        int index = songManager.calculateMoveToSongIndex(position);
        songManager.moveToSong(index);
        songManager.setFirstTime(false);
        playerActivity.playSong(songManager.getPlaySong());
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        System.out.println("Query : " + query + "submit");
        songManager.getSongBySearch(query);
        playerActivity.updatePlaylistFragment();
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        System.out.println("Query : " + newText);

        return false;
    }

    @Override
    public boolean onClose() {
        songManager.getAllSongs();
        playerActivity.updatePlaylistFragment();
        return true;
    }


    private class PlayerPagerAdapter extends FragmentStatePagerAdapter {

        public PlayerPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return playerActivity.setupPlayerPage(position);
        }

        @Override
        public int getCount() {
            return NUMBER_PLAYER_PAGE;
        }
    }

    public PlayerPagerAdapter getPlayerPagerAdapter() {
        return playerPagerAdapter;
    }

    public void setPlayerPagerAdapter(PlayerPagerAdapter playerPagerAdapter) {
        this.playerPagerAdapter = playerPagerAdapter;
    }
}
